package com.xbongbong.paas.help;

import com.aliyun.oss.OSSClient;
import com.aliyun.oss.model.ObjectMetadata;
import com.aliyun.oss.model.PutObjectResult;
import com.xbongbong.paas.constant.ConfigConstant;
import com.xbongbong.paas.toolbox.util.DateTimeUtil;
import com.xbongbong.paas.toolbox.util.MD5Util;
import com.xbongbong.paas.toolbox.util.StringUtil;
import com.xbongbong.pro.config.ProBaseConfig;
import com.xbongbong.saas.constant.StringConstant;
import com.xbongbong.saas.domain.entity.DingBundleRankEntity;
import com.xbongbong.saas.enums.mini.DingRobotManagePushEnum;
import org.apache.commons.io.FileUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.xhtmlrenderer.swing.Java2DRenderer;
import org.xhtmlrenderer.util.FSImageWriter;

import javax.annotation.Resource;
import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.text.DecimalFormat;
import java.util.List;
import java.util.Objects;
import java.util.Random;

/**
 * 应用模块名称<p>
 * 代码描述<p>
 * Company: 逍邦网络科技有限公司<p>
 *
 * @author chenshan
 * @version v1.0
 * @since 2020/10/14 4:29 下午
 */
@Component
public class CreateImageHelper {
    private static final Logger LOG = LoggerFactory.getLogger(CreateImageHelper.class);
    @Resource
    private ProBaseConfig proBaseConfig;
    
    /**
     * 文件系统相关 项目根路径
     */
    public static final String projectName = ProBaseConfig.getProjectName();
    
    public static String getProjectName() {
        return projectName;
    }
    
    public String upload(String key, byte[] imageByte) {
        
        try {
            long size = imageByte.length;
            InputStream content;
            content = new ByteArrayInputStream(imageByte);
            putObject(proBaseConfig.getBucketName(), key, content, size);
        } catch (IOException e) {
            
            e.printStackTrace();
            return "";
        }
    
        return proBaseConfig.getViewurl() + key;
    }
    
    public void putObject(String bucketName, String key,
                                 InputStream content, long size) throws FileNotFoundException {
        // 初始化OSSClient
        OSSClient client = new OSSClient(proBaseConfig.getEndpoint(), proBaseConfig.getOssAccessKeyId(), proBaseConfig.getAccessKeySecret());

        try {
            // 创建上传Object的Metadata
            ObjectMetadata meta = new ObjectMetadata();

            // 必须设置ContentLength
            meta.setContentLength(size);
            //文件类型
            int lastDotIndex = key.lastIndexOf(".");
            String fileType = key.substring(lastDotIndex + 1);
            meta.setContentType("image/" + fileType);

            // 上传Object.
            PutObjectResult result = client.putObject(bucketName, key, content,
                    meta);
        } catch (Exception e) {
            LOG.error("putObject error", e);
        } finally {
            client.shutdown();
        }
    }
    
    public String xhtmlToImage(String corpid, DingRobotManagePushEnum dingRobotManagePushEnum, List<DingBundleRankEntity> list, String userName, String avatar, Double amountStr,Long staticTime) throws IOException {
        if ( Objects.equals(avatar,"/images/default.jpg") ){
//            avatar = ConfigConstant.DEFAULT_PIC;
            avatar = ConfigConstant.DEFAULT_CIRCULAR_PIC;
        }
        String html = null;
        switch (dingRobotManagePushEnum){
            case MOST_ORDERS:
            case MAX_ORDER_AMOUNT:
                html = getHtmlContent(dingRobotManagePushEnum,userName,avatar,amountStr,staticTime);
                break;
            case PERFORMANCE_RANKING:
                html = getHtmlContent1(list,staticTime);
                break;
            default:
                return null;
        }
        //将xhtml文件转成图片
        String tmp = System.getProperty("java.io.tmpdir");
        Random random = new Random();
        String key = System.currentTimeMillis() + random.nextInt(1000) + ".jpg";
        File file = new File(tmp + "/"+ key);
        ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
        ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(html.getBytes("UTF-8"));
        FileUtils.copyInputStreamToFile(byteArrayInputStream, file);
        Java2DRenderer renderer = new Java2DRenderer(file, 1280, 960);
        BufferedImage img = renderer.getImage();
        FSImageWriter imageWriter = new FSImageWriter();
        imageWriter.setWriteCompressionQuality(1f);
        imageWriter.write(img, byteArrayOutputStream);
        String fileName = key.substring(key.lastIndexOf(File.separator) + 1, key.length());
        byte[] bytes = byteArrayOutputStream.toByteArray();
        String fileKey = getFileKey(corpid, fileName, MD5Util.md5(bytes));
        String url = upload(fileKey,bytes);
        return url;
    }
    
    public static String getHtmlContent(DingRobotManagePushEnum dingRobotManagePushEnum, String userName, String avatar, Double amountDou,Long staticTime) {
        String backgroundUrl = null;
        String amountStr = null;
        switch (dingRobotManagePushEnum){
            case MOST_ORDERS:
                backgroundUrl = StringConstant.MOST_ORDER_IMG_URL;
                int amountInt = Integer.parseInt(new DecimalFormat("#").format(amountDou));
                amountStr = amountInt+"单";
                break;
            case MAX_ORDER_AMOUNT:
                backgroundUrl = StringConstant.MOST_ORDER_AMOUNT_IMG_URL;
                amountStr = StringUtil.formatDouble(amountDou)+"元";
                break;
            default:
                break;
        }
        return String.format(StringConstant.MOST_HTML,backgroundUrl,avatar,userName,amountStr,DateTimeUtil.getStartOfHourString(staticTime));
    }
    
    public static String getHtmlContent1(List<DingBundleRankEntity> list, Long staticTime) {
        String breakground = StringConstant.PERFORMANCE_RANKING_ONLY_FIVE_IMG_URL;
        Integer count = list.size();
        switch (count){
            case 1:
                breakground = StringConstant.PERFORMANCE_RANKING_ONLY_ONE_IMG_URL;
                break;
            case 2:
                breakground = StringConstant.PERFORMANCE_RANKING_ONLY_TWO_IMG_URL;
                break;
            case 3:
                breakground = StringConstant.PERFORMANCE_RANKING_ONLY_THREE_IMG_URL;
                break;
            case 4:
                breakground = StringConstant.PERFORMANCE_RANKING_ONLY_FOUR_IMG_URL;
                break;
        }
        StringBuilder sb = new StringBuilder();
        for ( DingBundleRankEntity entity : list ) {
            String text = String.format(StringConstant.PERFORMANCE_RANKING_LIST_HTML,entity.getName(),StringUtil.formatDouble(entity.getAmount()));
            sb.append(text);
        }
        return String.format(StringConstant.PERFORMANCE_RANKING_HTML,breakground,DateTimeUtil.getStartOfHourString(staticTime),sb.toString());
    }
    
    /**
     * 生成一个文件上传的路径，作为key值
     *
     * @param userId   用户属性，给一个用户建立一个文件夹
     * @param filename 文件名
     * @param fileMd5  文件名md5哈希值
     * @return
     */
    public static String getFileKey(Object userId, String filename, String fileMd5) {
        int lastDotIndex = filename.lastIndexOf(".");
        String fileType = filename.substring(lastDotIndex + 1);
        
        String imageId = getProjectName() + "/" + userId + "/" + fileType + "/" + fileMd5 + "." + fileType;
        return imageId;
    }
}
